package cybertwin

import (
	//"fmt"
	"time"

	"github.com/panjf2000/gnet/v2"
	log "github.com/sirupsen/logrus"
)

type Cybertwin_Client struct {
	gnet.BuiltinEventEngine
	eng gnet.Engine
	//wg        *sync.WaitGroup
	cbt      *Cybertwin
	Shutdown bool
	Finish   bool
}

func (reqEv *Cybertwin_Client) OnBoot(eng gnet.Engine) gnet.Action {
	reqEv.eng = eng
	reqEv.Shutdown = false
	reqEv.Finish = false
	return gnet.None
}

func (reqEv *Cybertwin_Client) OnOpen(conn gnet.Conn) ([]byte, gnet.Action) {
	log.Infoln("[Gnet Client OnOpen]-Ready to request cloud service, sending data")

	return nil, gnet.None
}

func (reqEv *Cybertwin_Client) OnTraffic(conn gnet.Conn) gnet.Action {
	// 将收到的响应放入响应队列中
	reqRecord := conn.Context().(*Request_Record) // 这里的上下文类型为什么是Request_Record？因为在handler.go的forward_request方法中设置了
	buf, _ := conn.Next(-1)
	response := &Response_Record{
		providerID:   reqRecord.providerID,
		serviceID:    reqRecord.serviceID,
		requestID:    reqRecord.requestID,
		ueid:         reqRecord.ueid,
		data:         buf,
		dscp:         reqRecord.dscp,
		receive_time: time.Now(),
	}
	priority := getPriority(reqRecord.dscp)
	reqEv.cbt.enRespQueueAndForward(priority, response)

	// Attention: 如果响应是分段的怎么办？
	return gnet.Close
}

func (reqEv *Cybertwin_Client) OnClose(conn gnet.Conn, err error) gnet.Action {
	if err != nil {
		log.Infof("[Gnet Client OnClose]-error occurred on connection=%s, %v\n", conn.RemoteAddr().String(), err)
	}
	return gnet.None
}

// func (reqEv *requestEvents) OnTraffic() (duration time.Duration, action gnet.Action) {
// 	duration = time.Millisecond * 1

// 	// 处理超时重传的逻辑
// 	// to do

// 	action = gnet.None
// 	return
// }
